<?php
session_start();
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/includes/functions.php';

// 检查管理员权限
if (!isset($_SESSION['user_id']) || $_SESSION['username'] !== 'admin') {
    header('Location: login.php');
    exit;
}

// 处理状态更新
if ($_POST && isset($_POST['action'])) {
    $deposit_id = intval($_POST['deposit_id']);
    $action = $_POST['action'];
    $admin_note = trim($_POST['admin_note'] ?? '');
    
    try {
        if ($action === 'approve') {
            // 获取充值记录
            $stmt = $pdo->prepare("SELECT * FROM deposit_records WHERE id = ? AND status = 'pending'");
            $stmt->execute([$deposit_id]);
            $deposit = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($deposit) {
                $pdo->beginTransaction();
                
                // 更新用户余额
                $stmt = $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
                $stmt->execute([$deposit['amount'], $deposit['user_id']]);
                
                // 更新充值记录状态
                $stmt = $pdo->prepare("
                    UPDATE deposit_records 
                    SET status = 'completed', admin_note = ?, processed_at = NOW() 
                    WHERE id = ?
                ");
                $stmt->execute([$admin_note, $deposit_id]);
                
                $pdo->commit();
                $success_message = "充值申请已审批通过";
            }
        } elseif ($action === 'reject') {
            // 拒绝充值申请
            $stmt = $pdo->prepare("
                UPDATE deposit_records 
                SET status = 'failed', admin_note = ?, processed_at = NOW() 
                WHERE id = ? AND status = 'pending'
            ");
            $stmt->execute([$admin_note, $deposit_id]);
            $success_message = "充值申请已拒绝";
        }
    } catch (Exception $e) {
        if (isset($pdo) && $pdo->inTransaction()) {
            $pdo->rollBack();
        }
        $error_message = "操作失败: " . $e->getMessage();
    }
}

// 获取充值记录
$status_filter = $_GET['status'] ?? 'all';
$page = max(1, intval($_GET['page'] ?? 1));
$limit = 20;
$offset = ($page - 1) * $limit;

$where_clause = "WHERE 1=1";
$params = [];

if ($status_filter !== 'all') {
    $where_clause .= " AND status = ?";
    $params[] = $status_filter;
}

// 获取总数
$count_sql = "SELECT COUNT(*) FROM deposit_records $where_clause";
$stmt = $pdo->prepare($count_sql);
$stmt->execute($params);
$total_records = $stmt->fetchColumn();
$total_pages = ceil($total_records / $limit);

// 获取记录
$sql = "
    SELECT dr.*, u.username 
    FROM deposit_records dr 
    JOIN users u ON dr.user_id = u.id 
    $where_clause 
    ORDER BY dr.created_at DESC 
    LIMIT $limit OFFSET $offset
";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$deposits = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>充值管理 - 后台管理</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f5f5f5;
            line-height: 1.6;
        }
        
        .header {
            background: #2c3e50;
            color: white;
            padding: 1rem 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .nav-links {
            display: flex;
            gap: 1rem;
        }
        
        .nav-links a {
            color: white;
            text-decoration: none;
            padding: 0.5rem 1rem;
            border-radius: 4px;
            transition: background 0.3s;
        }
        
        .nav-links a:hover {
            background: rgba(255,255,255,0.1);
        }
        
        .container {
            max-width: 1200px;
            margin: 2rem auto;
            padding: 0 1rem;
        }
        
        .filters {
            background: white;
            padding: 1.5rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .filter-group {
            display: flex;
            gap: 1rem;
            align-items: center;
            flex-wrap: wrap;
        }
        
        .filter-group select, .filter-group input {
            padding: 0.5rem;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        .btn {
            padding: 0.5rem 1rem;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            font-size: 14px;
            transition: background 0.3s;
        }
        
        .btn-primary {
            background: #3498db;
            color: white;
        }
        
        .btn-success {
            background: #27ae60;
            color: white;
        }
        
        .btn-danger {
            background: #e74c3c;
            color: white;
        }
        
        .btn:hover {
            opacity: 0.9;
        }
        
        .table-container {
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        th, td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        
        th {
            background: #f8f9fa;
            font-weight: 600;
        }
        
        .status {
            padding: 0.25rem 0.5rem;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
        }
        
        .status-pending {
            background: #fff3cd;
            color: #856404;
        }
        
        .status-completed {
            background: #d4edda;
            color: #155724;
        }
        
        .status-failed {
            background: #f8d7da;
            color: #721c24;
        }
        
        .status-cancelled {
            background: #e2e3e5;
            color: #6c757d;
        }
        
        .actions {
            display: flex;
            gap: 0.5rem;
        }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
        }
        
        .modal-content {
            background: white;
            margin: 5% auto;
            padding: 2rem;
            border-radius: 8px;
            max-width: 500px;
            width: 90%;
        }
        
        .form-group {
            margin-bottom: 1rem;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
        }
        
        .form-group input, .form-group textarea {
            width: 100%;
            padding: 0.5rem;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        .pagination {
            margin-top: 1.5rem;
            text-align: center;
        }
        
        .pagination a {
            display: inline-block;
            padding: 0.5rem 1rem;
            margin: 0 0.25rem;
            text-decoration: none;
            border: 1px solid #ddd;
            border-radius: 4px;
            color: #333;
        }
        
        .pagination a.current {
            background: #3498db;
            color: white;
            border-color: #3498db;
        }
        
        .alert {
            padding: 1rem;
            margin-bottom: 1rem;
            border-radius: 4px;
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .random-code {
            font-family: 'Courier New', monospace;
            font-weight: bold;
            color: #e74c3c;
            font-size: 16px;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>充值管理系统</h1>
        <div class="nav-links">
            <a href="admin.php">返回管理面板</a>
            <a href="index.php">返回游戏</a>
            <a href="logout.php">退出登录</a>
        </div>
    </div>
    
    <div class="container">
        <?php if (isset($success_message)): ?>
            <div class="alert alert-success"><?php echo htmlspecialchars($success_message); ?></div>
        <?php endif; ?>
        
        <?php if (isset($error_message)): ?>
            <div class="alert alert-error"><?php echo htmlspecialchars($error_message); ?></div>
        <?php endif; ?>
        
        <!-- 筛选器 -->
        <div class="filters">
            <form method="GET" class="filter-group">
                <label>状态筛选:</label>
                <select name="status" onchange="this.form.submit()">
                    <option value="all" <?php echo $status_filter === 'all' ? 'selected' : ''; ?>>全部</option>
                    <option value="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>待审核</option>
                    <option value="completed" <?php echo $status_filter === 'completed' ? 'selected' : ''; ?>>已完成</option>
                    <option value="failed" <?php echo $status_filter === 'failed' ? 'selected' : ''; ?>>已拒绝</option>
                    <option value="cancelled" <?php echo $status_filter === 'cancelled' ? 'selected' : ''; ?>>已取消</option>
                </select>
            </form>
        </div>
        
        <!-- 充值记录表格 -->
        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户</th>
                        <th>金额</th>
                        <th>支付方式</th>
                        <th>随机码</th>
                        <th>状态</th>
                        <th>创建时间</th>
                        <th>处理时间</th>
                        <th>备注</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($deposits as $deposit): ?>
                    <tr>
                        <td><?php echo $deposit['id']; ?></td>
                        <td><?php echo htmlspecialchars($deposit['username']); ?></td>
                        <td>¥<?php echo number_format($deposit['amount'], 2); ?></td>
                        <td>
                            <?php 
                            $payment_methods = [
                                'alipay' => '支付宝',
                                'wechat' => '微信支付',
                                'bank' => '银行转账'
                            ];
                            echo $payment_methods[$deposit['payment_method']] ?? $deposit['payment_method'];
                            ?>
                        </td>
                        <td class="random-code"><?php echo $deposit['random_code']; ?></td>
                        <td>
                            <span class="status status-<?php echo $deposit['status']; ?>">
                                <?php
                                $status_texts = [
                                    'pending' => '待审核',
                                    'completed' => '已完成',
                                    'failed' => '已拒绝',
                                    'cancelled' => '已取消'
                                ];
                                echo $status_texts[$deposit['status']] ?? $deposit['status'];
                                ?>
                            </span>
                        </td>
                        <td><?php echo date('Y-m-d H:i:s', strtotime($deposit['created_at'])); ?></td>
                        <td><?php echo $deposit['processed_at'] ? date('Y-m-d H:i:s', strtotime($deposit['processed_at'])) : '-'; ?></td>
                        <td><?php echo htmlspecialchars($deposit['admin_note'] ?: '-'); ?></td>
                        <td>
                            <?php if ($deposit['status'] === 'pending'): ?>
                            <div class="actions">
                                <button class="btn btn-success" onclick="showApprovalModal(<?php echo $deposit['id']; ?>, '<?php echo htmlspecialchars($deposit['username']); ?>', <?php echo $deposit['amount']; ?>)">通过</button>
                                <button class="btn btn-danger" onclick="showRejectionModal(<?php echo $deposit['id']; ?>, '<?php echo htmlspecialchars($deposit['username']); ?>', <?php echo $deposit['amount']; ?>)">拒绝</button>
                            </div>
                            <?php else: ?>
                            <span class="status status-<?php echo $deposit['status']; ?>">已处理</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <!-- 分页 -->
        <?php if ($total_pages > 1): ?>
        <div class="pagination">
            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                <a href="?page=<?php echo $i; ?>&status=<?php echo $status_filter; ?>" 
                   class="<?php echo $i === $page ? 'current' : ''; ?>">
                    <?php echo $i; ?>
                </a>
            <?php endfor; ?>
        </div>
        <?php endif; ?>
    </div>
    
    <!-- 审批模态框 -->
    <div id="approvalModal" class="modal">
        <div class="modal-content">
            <h3>审批充值申请</h3>
            <form method="POST">
                <input type="hidden" name="deposit_id" id="approveDepositId">
                <input type="hidden" name="action" value="approve">
                
                <div class="form-group">
                    <label>用户:</label>
                    <input type="text" id="approveUsername" readonly>
                </div>
                
                <div class="form-group">
                    <label>金额:</label>
                    <input type="text" id="approveAmount" readonly>
                </div>
                
                <div class="form-group">
                    <label>管理员备注:</label>
                    <textarea name="admin_note" placeholder="请填写审批备注..."></textarea>
                </div>
                
                <div class="actions">
                    <button type="submit" class="btn btn-success">确认通过</button>
                    <button type="button" class="btn" onclick="closeModal('approvalModal')">取消</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 拒绝模态框 -->
    <div id="rejectionModal" class="modal">
        <div class="modal-content">
            <h3>拒绝充值申请</h3>
            <form method="POST">
                <input type="hidden" name="deposit_id" id="rejectDepositId">
                <input type="hidden" name="action" value="reject">
                
                <div class="form-group">
                    <label>用户:</label>
                    <input type="text" id="rejectUsername" readonly>
                </div>
                
                <div class="form-group">
                    <label>金额:</label>
                    <input type="text" id="rejectAmount" readonly>
                </div>
                
                <div class="form-group">
                    <label>拒绝原因:</label>
                    <textarea name="admin_note" placeholder="请填写拒绝原因..." required></textarea>
                </div>
                
                <div class="actions">
                    <button type="submit" class="btn btn-danger">确认拒绝</button>
                    <button type="button" class="btn" onclick="closeModal('rejectionModal')">取消</button>
                </div>
            </form>
        </div>
    </div>
    
    <script>
        function showApprovalModal(depositId, username, amount) {
            document.getElementById('approveDepositId').value = depositId;
            document.getElementById('approveUsername').value = username;
            document.getElementById('approveAmount').value = '¥' + amount;
            document.getElementById('approvalModal').style.display = 'block';
        }
        
        function showRejectionModal(depositId, username, amount) {
            document.getElementById('rejectDepositId').value = depositId;
            document.getElementById('rejectUsername').value = username;
            document.getElementById('rejectAmount').value = '¥' + amount;
            document.getElementById('rejectionModal').style.display = 'block';
        }
        
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }
        
        // 点击模态框外部关闭
        window.onclick = function(event) {
            if (event.target.classList.contains('modal')) {
                event.target.style.display = 'none';
            }
        }
    </script>
</body>
</html>
